package com.dushibao.manage.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserServiceImpl;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "DownLoadDataServlet",urlPatterns = "/downLoadUserDataServlet")
public class DownLoadUserDataServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @SneakyThrows
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");

        String ids = request.getParameter("ids");
        List<Long> userIds = new ArrayList<>();

        if(StrUtil.isNotEmpty(ids)){
            for (String s : ids.split(",")) {
                userIds.add(Long.parseLong(s));
            }
        }

        List<User> users = userService.list(userIds);

        //Create blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
        //Create a blank sheet
        XSSFSheet spreadsheet = workbook.createSheet(" 用户信息 ");
        XSSFRow title = spreadsheet.createRow(0);
        Cell id = title.createCell(0);
        id.setCellValue("ID");
        Cell addTime = title.createCell(1);
        addTime.setCellValue("入库时间");
        Cell userName = title.createCell(2);
        userName.setCellValue("用户名");
        Cell password = title.createCell(3);
        password.setCellValue("密码");
        if(CollUtil.isNotEmpty(users)){
            for (int i = 0; i < users.size(); i++) {
                XSSFRow data = spreadsheet.createRow(i+1);
                data.createCell(0).setCellValue(users.get(i).getId());
                data.createCell(1).setCellValue(LocalDateTimeUtil.format(users.get(i).getAddTime(),"yyyy-MM-dd HH:mm:ss"));
                data.createCell(2).setCellValue(users.get(i).getUserName());
                data.createCell(3).setCellValue(users.get(i).getPassword());
            }
        }

        //得到下载的文件名
        String filename = "users.xlsx";
        //设置文件编码
        filename = URLEncoder.encode(filename, "UTF-8"); //转成utf-8 ，返回String

        //创建字节输出流
        OutputStream out = response.getOutputStream(); //此方法获取输出流对象

        //告知客户端下载文件 启动下载 规定后缀名
        response.setHeader("content-disposition", "attachment;filename="+filename);

        workbook.write(out);

        out.close();
    }
}
